const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

const Mongoose = require('mongoose')
const Redis = require('koa-redis')
// 样式优化
const bodyParser = require('koa-bodyparser')
const json = require('koa-json')
// 登陆验证
const session = require('koa-generic-session')
const passport = require('./interface/utils/passport')
// 配置项
const DbRedisConfig = require('./dbs/config')
// 接口路由
const userRouter = require('./interface/user')

const app = new Koa()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

app.keys = ['bigfu', 'keyskeys']
app.proxy = true
// json中间件
app.use(json())
// session中间件
app.use(session({
  key: 'bigfu',
  prefix: 'bigfu:uid',
  store: new Redis()
}))
//bodyparser中间件
app.use(bodyParser({
  extendTypes: ['json', 'form', 'text']
}))
// 数据库链接
Mongoose.connect(DbRedisConfig.dbs, {
  useNewUrlParser: true
})
// 登陆相关
app.use(passport.initialize())
app.use(passport.session())
async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  await nuxt.ready()
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }
  // 路由表
  app.use(userRouter.routes()).use(userRouter.allowedMethods())
  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
